﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JXT.PrimaryKey.Batman.Validation;
using JXT.PrimaryKey.Batman.Collections;
using JXT.PrimaryKey.Batman.Domain.Models;
using JXT.PrimaryKey.Batman.Domain.Services;
using JXT.PrimaryKey.Batman.Domain.Specifications;
using JXT.PrimaryKey.Batman.Domain.UserSystem.Models;
using JXT.PrimaryKey.Batman.Domain.UserSystem.Repositories;

namespace JXT.PrimaryKey.Batman.Domain.UserSystem.Services.Default
{
    public class AuthorityTemplateService : CachedServiceBase<AuthorityTemplate>, IAuthorityTemplateService
    {
        private static readonly string _cacheKey = "list";

        public void Save(AuthorityTemplate entity)
        {
            var result = Validator.Validate(entity);
            if (!result.IsValid)
                throw new ValidationException("entity validate error!", result.Errors);
            if (entity.Id > 0)
                LoadRepository<IAuthorityTemplateRepository>().Update(entity);
            else
                LoadRepository<IAuthorityTemplateRepository>().Add(entity);
            ClearCache();
        }

        public void Delete(AuthorityTemplate entity)
        {
            LoadRepository<IAuthorityTemplateRepository>().Delete(entity.Id);
            ClearCache();
        }

        public IEnumerable<AuthorityTemplate> GetList()
        {
            var list = Cache.Get(CacheSpace, _cacheKey) as IEnumerable<AuthorityTemplate>;
            if (list == null)
            {
                list = LoadRepository<IAuthorityTemplateRepository>().GetList(null);
                Cache.Add(CacheSpace, _cacheKey, list);
            }
            return list;
        }

        public void FillAuthority(Authority authority)
        {
            if (authority != null)
            {
                var template = GetList().FirstOrDefault(e => e.Id == authority.TemplateId);
                if (template != null)
                {
                    authority.Name = template.Name;
                    authority.Summary = template.Summary;
                    authority.Type = template.Type;
                    authority.Priority = template.Priority;
                }
            }
        }

        public void FillAuthorityEnumerable(IEnumerable<Authority> source)
        {
            if (source != null)
            {
                foreach (var item in source)
                {
                    FillAuthority(item);
                }
            }
        }
    }
}
